//------------------------------------------------------------------------------
#include <QtGui>
#include <QMessageBox>
#include <QDate>
#include <QDesktopServices>
#include <QUuid>
#include <QClipboard>
#include <QSqlRecord>
#include <QList>
#include "CFindFrm.h"
#include "CComboResultFrm.h"
#include "CDerniereActionFrm.h"
#include "CCalendrierFrm.h"
#include "CMyTextEdit.h"
#include "CTextEditDelegate.h"
#include "CTimeEditDelegate.h"
#include "CGestionFavorisProspectFrm.h"
#include "CProspectFrm.h"
#include "version.h"
#include "CMySQL.h"
#include "CHelp.h"
#include "CMimeType.h"
//------------------------------------------------------------------------------
CProspectFrm::CProspectFrm(QString name, QString lastCode, CMainFrm *parent) : CMyMainWindow(name, parent)
{
	setActionCur(CGlobal::acConstruct);
	
	setupUi(this);
	
	setStatusBar(NULL);
	
	mainFrm=parent;
	masterTable="prospect";
	primaryKey="code";
	derniereRequete="";
	sizeFrmRecherche=QSize();
	posFrmRecherche=QPoint();
	colSortFrmRecherche=0;
	sortOrderFrmRecherche=Qt::AscendingOrder;
	lastLigneFrmRecherche=0;
	curContactNum=-1;
	effectif->addItem(tr("1 à 5"));
	effectif->addItem(tr("6 à 9"));
	effectif->addItem(tr("10 à 19"));
	effectif->addItem(tr("20 à 49"));
	effectif->addItem(tr("50 à 99"));
	effectif->addItem(tr("100 à 199"));
	effectif->addItem(tr("plus de 200"));
	
	tabWidget->removeTab(0);
	
	createGrilleActions();
	createGrilleContact();
	createGrilleDevis();
	createGrilleDocuments();
	createGrilleTva();

	commentaires=new CTextWidget(this);
	commentaires->setChamp("commentaires");
	commentaires->setTable("prospect");
	tabWidget->addTab(commentaires, "Commentaires");
	connect(commentaires, SIGNAL(textChanged()), this, SLOT(onChange()));
	connect(commentaires, SIGNAL(invokeHelp(CChamp*)), this, SLOT(onInvokeHelp(CChamp*)));
	
	makeMenu();
	
	loadSchema();
	
	if(CMySQL::getInstance()->getNbEnregistrement(masterTable) == 0)
	{
		setActionCur(CGlobal::acTableVide);
	}else
	{
		if(!chargeDonnees(lastCode, CGlobal::seNone)) chargeDonnees("", CGlobal::sePremier);
	}
}
//------------------------------------------------------------------------------
void CProspectFrm::setActionCur(CGlobal::EAction action)
{
	actionCur=action;
	
	switch(actionCur)
	{
		case CGlobal::acNone:
			actPremiereFiche->setEnabled(true);
			actFichePrecedente->setEnabled(true);
			actFicheSuivante->setEnabled(true);
			actDerniereFiche->setEnabled(true);
			
			actAjouter->setEnabled(true);
			actSupprimer->setEnabled(true);
			
			actValider->setEnabled(false);
			actAnnuler->setEnabled(false);
			
			actRechercheUneFiche->setEnabled(true);
			actDerniereRecherche->setEnabled(derniereRequete != "");
			
			actAbonneEMailing->setEnabled(true);
			
			actDerniereAction->setEnabled(true);
			actProspectsSansAction->setEnabled(true);
			
			actCopieAdresse->setEnabled(true);
			
			actFavoris->setEnabled(true);
			
			enableChamps(true);
			code->setEnabled(false);
			tabWidget->setEnabled(true);
			effectif->setEnabled(true);
			break;
		case CGlobal::acTableVide:
			actPremiereFiche->setEnabled(false);
			actFichePrecedente->setEnabled(false);
			actFicheSuivante->setEnabled(false);
			actDerniereFiche->setEnabled(false);
			
			actAjouter->setEnabled(true);
			actSupprimer->setEnabled(false);
			
			actValider->setEnabled(false);
			actAnnuler->setEnabled(false);
			
			actRechercheUneFiche->setEnabled(false);
			actDerniereRecherche->setEnabled(false);
			
			actAbonneEMailing->setEnabled(false);
			
			actDerniereAction->setEnabled(false);
			actProspectsSansAction->setEnabled(false);
			
			actCopieAdresse->setEnabled(false);
			
			actFavoris->setEnabled(false);
			
			clearChamps();
			enableChamps(false);
			creation->setValue("");
			
			actionWidget->setRowCount(0);
			contactWidget->setRowCount(0);
			devisWidget->setRowCount(0);
			documentsWidget->setRowCount(0);
			
			tabWidget->setEnabled(false);
			effectif->setEnabled(false);
			break;
		case CGlobal::acAjout:
			clearChamps();
			initChamps();
			enableChamps(true);
			code->setFocus();
			actionWidget->setRowCount(0);
			
			actPremiereFiche->setEnabled(false);
			actFichePrecedente->setEnabled(false);
			actFicheSuivante->setEnabled(false);
			actDerniereFiche->setEnabled(false);
			
			actAjouter->setEnabled(false);
			actSupprimer->setEnabled(false);
			
			actValider->setEnabled(true);
			actAnnuler->setEnabled(true);
			
			actRechercheUneFiche->setEnabled(false);
			actDerniereRecherche->setEnabled(false);
			
			actAbonneEMailing->setEnabled(false);
			
			actDerniereAction->setEnabled(false);
			actProspectsSansAction->setEnabled(false);
			
			actCopieAdresse->setEnabled(false);
			
			actFavoris->setEnabled(false);
			
			tabWidget->setEnabled(false);
			effectif->setEnabled(true);
			break;
		case CGlobal::acModif:
			actPremiereFiche->setEnabled(false);
			actFichePrecedente->setEnabled(false);
			actFicheSuivante->setEnabled(false);
			actDerniereFiche->setEnabled(false);
			
			actAjouter->setEnabled(false);
			actSupprimer->setEnabled(false);
			
			actValider->setEnabled(true);
			actAnnuler->setEnabled(true);
			
			actRechercheUneFiche->setEnabled(false);
			actDerniereRecherche->setEnabled(false);
			
			actAbonneEMailing->setEnabled(false);
			
			actDerniereAction->setEnabled(false);
			actProspectsSansAction->setEnabled(false);
			
			actCopieAdresse->setEnabled(false);
			
			actFavoris->setEnabled(false);
			
			tabWidget->setEnabled(true);
			effectif->setEnabled(true);
			break;
		default:
			break;
	}
}
//------------------------------------------------------------------------------
CGlobal::EAction CProspectFrm::getActionCur(void)
{
	return actionCur;
}
//------------------------------------------------------------------------------
void CProspectFrm::closeEvent(QCloseEvent * event)
{
	if(getActionCur() != CGlobal::acNone && getActionCur() != CGlobal::acTableVide)
	{
		QMessageBox msgBox(	QMessageBox::Warning, tr("Attention"), 
							tr("Veuillez annuler ou valider avant de sortir"), QMessageBox::Ok);
		msgBox.exec();	
		
		event->ignore();
	}else
	{
		emit quit(objectName(), curCode);
		event->accept();
	}
}
//------------------------------------------------------------------------------
void CProspectFrm::resizeEvent(QResizeEvent * event)
{
	QSize wndSize=event->size();
	int height=centralWidget()->size().height()-270;
	
	if(height > 0)
	{
		tabWidget->setFixedSize(wndSize.width()-20, height);
		tabWidget->move(10, 260);
	}
	
	QMainWindow::resizeEvent(event);
}
//------------------------------------------------------------------------------
void CProspectFrm::createGrilleActions(void)
{
	CTextEditDelegate *delegateCmtr=new CTextEditDelegate();
	CTimeEditDelegate *delegateTime=new CTimeEditDelegate();
	QList<CColumnModel *> *columnModel=new QList<CColumnModel *>();
	
	columnModel->append(new CColumnModelInt(cnaNum, "numeroAction", tr("Numéro"), Qt::AlignRight, NULL, Qt::ItemIsEnabled));
	columnModel->append(new CColumnModelString(cnaAction, "action", tr("Action")));
	columnModel->append(new CColumnModelDate(cnaDate, "dateAction", tr("Date"), Qt::AlignRight, 
			new QIcon(":coMexpert/images/1day.png"), Qt::ItemIsEnabled));
	columnModel->append(new CColumnModelTime(cnaHeure, "heureAction", tr("Heure"), Qt::AlignRight));
	columnModel->append(new CColumnModelString(cnaQui, "qui", tr("Par"), Qt::AlignLeft, NULL, Qt::ItemIsEnabled));
	columnModel->append(new CColumnModelString(cnaInterloc, "interlocuteur", tr("Iterlocuteur"), Qt::AlignLeft,
			new QIcon(":coMexpert/images/aim_protocol.png"), Qt::ItemIsEnabled));
	columnModel->append(new CColumnModelString(cnaCommentaires, "commentaires", tr("Commentaires")));
	
	actionWidget=new CGrilleWidget(columnModel, this);
	connect(actionWidget, SIGNAL(ajoute(bool&)), this, SLOT(ajouteAction(bool&)));
	connect(actionWidget, SIGNAL(supprime(int, bool&)), this, SLOT(supprimeAction(int, bool&)));
	connect(actionWidget, SIGNAL(cellChanged(int, int)), this, SLOT(modifiAction(int, int)));
	connect(actionWidget, SIGNAL(cellDoubleClicked(int, int)), this, SLOT(actionDoubleClicked(int, int)));
	connect(actionWidget, SIGNAL(beforeInsert(const QSqlQuery *, CMyTableWidgetItem *)), this, 
			SLOT(beforeInsertAction(const QSqlQuery *, CMyTableWidgetItem *)));
	tabWidget->addTab(actionWidget, QIcon(":coMexpert/images/aktion.png"), tr("Actions"));
	
	actionWidget->setColumnWidth(cnaNum, 80);
	actionWidget->setColumnWidth(cnaAction, 175);
	actionWidget->setColumnWidth(cnaInterloc, 175);
	actionWidget->setColumnWidth(cnaCommentaires, 500);
	
	actionWidget->setItemDelegateForColumn(cnaCommentaires, delegateCmtr);
	actionWidget->setItemDelegateForColumn(cnaHeure, delegateTime);
}
//------------------------------------------------------------------------------
void CProspectFrm::loadGrilleActions(void)
{
	CGlobal::EAction oldAction=getActionCur();
	QString requete;
	QSqlQuery *query;
	
	setActionCur(CGlobal::acAfficheLigne);
	
	requete="SELECT numeroAction, action, dateAction, heureAction, qui, interlocuteur, commentaires, auto ";
	requete+="FROM actionsProspect WHERE prospect=\""+curCode+"\" ORDER BY dateAction DESC, heureAction DESC";
	
	if(CMySQL::getInstance()->execQuery(requete, &query))
	{
		actionWidget->loadGrille(query);
	}
	delete query;
	
	setActionCur(oldAction);
}
//------------------------------------------------------------------------------
void CProspectFrm::createGrilleContact(void)
{
	QList<CColumnModel *> *columnModel=new QList<CColumnModel *>();
	
	columnModel->append(new CColumnModelInt(cncpNum, "numero", tr("Numéro"), Qt::AlignRight, NULL, Qt::ItemIsEnabled));
	columnModel->append(new CColumnModelString(cncpDefaut, "defaut", tr("Déf."), Qt::AlignCenter, NULL, Qt::ItemIsEnabled));
	columnModel->append(new CColumnModelString(cncpNom, "nom", tr("Nom")));
	columnModel->append(new CColumnModelString(cncpFonction, "fonction", tr("Fonction")));
	columnModel->append(new CColumnModelString(cncpTel, "telephone", tr("Téléphone(s)")));
	columnModel->append(new CColumnModelString(cncpFax, "fax", tr("Fax")));
	columnModel->append(new CColumnModelString(cncpMail, "mail", tr("Mail")));
	
	contactWidget=new CGrilleWidget(columnModel, this);
	connect(contactWidget, SIGNAL(ajoute(bool&)), this, SLOT(ajouteContact(bool&)));
	connect(contactWidget, SIGNAL(supprime(int, bool&)), this, SLOT(supprimeContact(int, bool&)));
	connect(contactWidget, SIGNAL(cellChanged(int, int)), this, SLOT(modifiContact(int, int)));
	connect(contactWidget, SIGNAL(customContextMenuRequested(const QPoint &)),
			this, SLOT(tableCustomContextMenuRequested(const QPoint &)));
	connect(contactWidget, SIGNAL(cellDoubleClicked(int, int)), this, SLOT(contactDoubleClicked(int, int)));
	connect(contactWidget, SIGNAL(beforeChangeRecord(const QSqlQuery *, int)), this, SLOT(beforeChangeRecordContact(const QSqlQuery *, int)));
	tabWidget->addTab(contactWidget, QIcon(":coMexpert/images/aim_protocol.png"), tr("Contacts"));
	
	contactWidget->setColumnWidth(cncpNum, 80);
	contactWidget->setColumnWidth(cncpDefaut, 30);
	contactWidget->setColumnWidth(cncpNom, 200);
	contactWidget->setColumnWidth(cncpFonction, 200);
	contactWidget->setColumnWidth(cncpMail, 250);
}
//------------------------------------------------------------------------------
void CProspectFrm::loadGrilleContact(void)
{
	CGlobal::EAction oldAction=getActionCur();
	QString requete;
	QSqlQuery *query;
	
	setActionCur(CGlobal::acAfficheLigne);
	
	requete="SELECT numero, defaut, nom, fonction, telephone, fax, mail ";
	requete+="FROM contactProspect WHERE prospect=\""+curCode+"\" ORDER BY numero";
	
	contact->setText("");
	fonction->setText("");
	mail->setText("");
	
	if(CMySQL::getInstance()->execQuery(requete, &query)) {
		int nb=contactWidget->loadGrille(query);
		tabWidget->setTabText(etnContacts, tr("Contacts")+" ("+QString::number(nb)+")");
	}
	delete query;
	
	setActionCur(oldAction);
}
//------------------------------------------------------------------------------
void CProspectFrm::createGrilleDevis(void)
{
	QList<CColumnModel *> *columnModel=new QList<CColumnModel *>();
	
	columnModel->append(new CColumnModelInt(cndpNum, "code", tr("Numéro"), Qt::AlignRight, NULL, Qt::ItemIsEnabled));
	columnModel->append(new CColumnModelString(cndpTitre, "titre", tr("Titre"), Qt::AlignLeft, NULL, Qt::ItemIsEnabled));
	columnModel->append(new CColumnModelDate(cndpDate, "creation", tr("Date"), Qt::AlignRight, NULL, Qt::ItemIsEnabled));
	columnModel->append(new CColumnModelString(cndpPar, "user", tr("Fait par"), Qt::AlignLeft, NULL, Qt::ItemIsEnabled));
	columnModel->append(new CColumnModelDouble(cndpMontant, "montant", tr("Montant"), Qt::AlignRight, NULL, Qt::ItemIsEnabled));
	columnModel->append(new CColumnModelString(cndpStatus, "status", tr("Status"), Qt::AlignLeft, NULL, Qt::ItemIsEnabled));
	
	
	devisWidget=new CGrilleWidget(columnModel, this, false);
	connect(devisWidget, SIGNAL(cellDoubleClicked(int, int)), this, SLOT(devisDoubleClicked(int, int)));
	tabWidget->addTab(devisWidget, QIcon(":coMexpert/images/colorize.png"), tr("Devis"));
	
	devisWidget->setColumnWidth(cndpTitre, 300);
}
//------------------------------------------------------------------------------
void CProspectFrm::loadGrilleDevis(void)
{
	CGlobal::EAction oldAction=getActionCur();
	QString requete;
	QSqlQuery *query;
	
	setActionCur(CGlobal::acAfficheLigne);
	
	requete="SELECT code, titre, creation, user, IFNULL(sum(quantite*prixUnitaireHt), 0.00) as montant, status ";
	requete+="FROM teteDevis LEFT JOIN ligneDevis ON devis=code ";
	requete+="WHERE codeProspect=\""+curCode+"\" GROUP BY code ORDER BY creation DESC";
	
	if(CMySQL::getInstance()->execQuery(requete, &query))
	{
		devisWidget->loadGrille(query);
	}
	delete query;
	
	setActionCur(oldAction);
}
//------------------------------------------------------------------------------
void CProspectFrm::createGrilleDocuments(void)
{
	QList<CColumnModel *> *columnModel=new QList<CColumnModel *>();
	
	columnModel->append(new CColumnModelInt(cnopNum, "numero", tr("Numéro"), Qt::AlignRight, NULL, Qt::ItemIsEnabled));
	columnModel->append(new CColumnModelString(cnopDescription, "description", tr("Description")));
	columnModel->append(new CColumnModelString(cnopDocument, "fileName", tr("Document"), Qt::AlignLeft, new 	QIcon(":coMexpert/images/doc.png"), Qt::ItemIsEnabled));
	
	documentsWidget=new CGrilleWidget(columnModel, this);
	connect(documentsWidget, SIGNAL(ajoute(bool&)), this, SLOT(ajouteDocument(bool&)));
	connect(documentsWidget, SIGNAL(supprime(int, bool&)), this, SLOT(supprimeDocument(int, bool&)));
	connect(documentsWidget, SIGNAL(cellChanged(int, int)), this, SLOT(modifiDocument(int, int)));
	connect(documentsWidget, SIGNAL(cellDoubleClicked(int, int)), this, SLOT(documentDoubleClicked(int, int)));
	tabWidget->addTab(documentsWidget, QIcon(":coMexpert/images/doc.png"), tr("Documents"));
	
	documentsWidget->setColumnWidth(cnopNum, 80);
	documentsWidget->setColumnWidth(cnopDescription, 400);
	documentsWidget->setColumnWidth(cnopDocument, 200);
}
//------------------------------------------------------------------------------
void CProspectFrm::loadGrilleDocuments(void)
{
	CGlobal::EAction oldAction=getActionCur();
	QString requete;
	QSqlQuery *query;
	
	setActionCur(CGlobal::acAfficheLigne);
	
	requete="SELECT numero, description, fileName ";
	requete+="FROM documentsProspect WHERE prospect=\""+curCode+"\" ORDER BY numero";
	
	if(CMySQL::getInstance()->execQuery(requete, &query))
	{
		documentsWidget->loadGrille(query);
	}
	delete query;
	
	setActionCur(oldAction);
}
//------------------------------------------------------------------------------
void CProspectFrm::createGrilleTva(void) {
	QList<CColumnModel *> *columnModel=new QList<CColumnModel *>();
	
	columnModel->append(new CColumnModelInt(ctnpId, "id", tr("Identifiant"), Qt::AlignRight, NULL, Qt::ItemIsEnabled));
	columnModel->append(new CColumnModelString(ctnpNom, "nom", tr("Nom"), Qt::AlignLeft));
	columnModel->append(new CColumnModelDouble(ctnpTaux, "taux", tr("Taux"), Qt::AlignRight, NULL, (Qt::ItemFlags)63, QVariant(3)));
	columnModel->append(new CColumnModelString(ctnpCompteComptable, "compteComptable", tr("Compte Comptable")));
	
	tvaWidget=new CGrilleWidget(columnModel, this, false);
	connect(tvaWidget, SIGNAL(cellChanged(int, int)), this, SLOT(modifiTva(int, int)));
	tabWidget->addTab(tvaWidget, tr("Tva"));
	
	tvaWidget->setColumnWidth(ctnpNom, 250);
	tvaWidget->setColumnWidth(ctnpCompteComptable, 180);
}
//------------------------------------------------------------------------------
void CProspectFrm::loadGrilleTva(void) {
	CGlobal::EAction oldAction=getActionCur();
	QString requete;
	QSqlQuery *query;
	
	setActionCur(CGlobal::acAfficheLigne);
	
	requete="SELECT id, nom, taux, compteComptable FROM tvaProspect WHERE codeProspect=\""+curCode+"\" ORDER BY idTva";
	
	if(CMySQL::getInstance()->execQuery(requete, &query)) {
		tvaWidget->loadGrille(query);
	}
	
	delete query;
	
	setActionCur(oldAction);
}
//------------------------------------------------------------------------------
void CProspectFrm::makeMenu(void)
{
	popupMenu=new QMenu(contactWidget);
	
	actActionFromContact=new QAction(QIcon(":coMexpert/images/bookmark_add.png"), tr("&Créer une action pour ce contact"), this);
	actActionFromContact->setIconVisibleInMenu(true);
	connect(actActionFromContact, SIGNAL(triggered()), this, SLOT(actActionFromContact_triggered()));
	
	actMailFromContact=new QAction(QIcon(":coMexpert/images/mail_post_to.png"), tr("&Envoyer un mail au contact"), this);
	actMailFromContact->setIconVisibleInMenu(true);
	connect(actMailFromContact, SIGNAL(triggered()), this, SLOT(actMailFromContact_triggered()));
	
	popupMenu->addAction(actActionFromContact);
	popupMenu->addAction(actMailFromContact);
	
	favorisMenu=new QMenu(this);
	
	actNouveauFavoris=new QAction(QIcon(":coMexpert/images/bookmark_add.png"), tr("&Ajouter ce prospect comme favoris"), this);
	actNouveauFavoris->setData(QVariant::Int);
	actNouveauFavoris->setIconVisibleInMenu(true);
	connect(actNouveauFavoris, SIGNAL(triggered()), this, SLOT(actNouveauFavoris_triggered()));
	
	actGestFavoris=new QAction(QIcon(":coMexpert/images/bookmark_toolbar.png"), tr("&Gestion des favoris"), this);
	actGestFavoris->setIconVisibleInMenu(true);
	connect(actGestFavoris, SIGNAL(triggered()), this, SLOT(actGestFavoris_triggered()));
	
	actSeparator=favorisMenu->addSeparator();
	favorisMenu->addAction(actNouveauFavoris);
	favorisMenu->addAction(actGestFavoris);
	loadFavoris(favorisMenu);
	
	actFavoris->setMenu(favorisMenu);
}
//------------------------------------------------------------------------------
void CProspectFrm::loadFavoris(QMenu *menu, int *parent) {
	QString requete;
	QSqlQuery *query;
	
	requete="SELECT fp.id, fp.prospect, fp.nom AS folderName, p.nom AS prospectName ";
	requete+="FROM favorisProspect AS fp ";
	requete+="LEFT JOIN prospect AS p ON p.code=fp.prospect ";
	requete+="WHERE user=\""+CMySQL::getInstance()->getUser()+"\" AND ";
	requete+="parent "+(parent == 0 ? "IS NULL" : "= "+QString::number(*parent))+" ";
	requete+="ORDER BY prospect";
	
	if(CMySQL::getInstance()->execQuery(requete, &query)) {
		while(query->next()) {
			QSqlRecord rec=query->record();
			
			if(rec.value("prospect").isNull()) {
				int p=rec.value("id").toInt();
				QMenu *nMenu=menu;
				
				if(!rec.value("folderName").toString().isNull()) {
					nMenu=new QMenu(rec.value("folderName").toString());
				
					nMenu->setIcon(QIcon(":coMexpert/images/folder.png"));
				
					menu->insertMenu(actSeparator, nMenu);
					
					QAction *act=new QAction(QIcon(":coMexpert/images/bookmark_add.png"), tr("&Ajouter ce prospect comme favoris"), this);
					act->setIconVisibleInMenu(true);
					act->setData(rec.value("id"));
					connect(act, SIGNAL(triggered()), this, SLOT(actNouveauFavoris_triggered()));
					nMenu->addAction(act);
					nMenu->addSeparator();
				}
				
				loadFavoris(nMenu, &p);
			}else {
				QAction * act=new QAction(rec.value("prospectName").toString(), this);
				act->setData(rec.value("prospect").toString());
				connect(act, SIGNAL(triggered()), this, SLOT(actSelectFavoris_triggered()));
				
				menu->insertAction(actSeparator, act);
			}
		}
	}
	delete query;
}
//------------------------------------------------------------------------------
void CProspectFrm::dropFavoris(QMenu *menu)
{
	QList<QAction*> listActions=menu->actions();
	QAction *act;
	int i=0;
	
	for(i=0;i<listActions.size();i++) {
		act=listActions[i];
		
		if(act == actSeparator) {
			break;
		}
		if(act->menu() != 0) {
			dropFavoris(act->menu());
		}
		favorisMenu->removeAction(act);
		delete act;
	}
}
//------------------------------------------------------------------------------
void CProspectFrm::creerDocument(int row)
{
	setCursor(Qt::WaitCursor);
	QString fileName=QFileDialog::getOpenFileName(this, tr("Choisir un fichier"));
			
	if(fileName != "")
	{
		QFileInfo fi(fileName);
		QString mimeType=CMimeType::getInstance()->getMimeType(fi.suffix());
		QFile file(fileName);
					
		fileName=fi.fileName();
					
		if(file.open(QIODevice::ReadOnly))
		{
			QByteArray ba=file.readAll();
			QString requete;
			QString data="0x"+QString(ba.toHex());
						
			file.close();
						
			requete="UPDATE documentsProspect ";
			requete+="SET document="+data+", typeMime=\""+mimeType+"\", fileName=\""+fileName+"\", ";
			requete+="modificateur=\""+CMySQL::getInstance()->getUser()+"\", modification=CURDATE() ";
			requete+="WHERE prospect=\""+curCode+"\" AND numero="+documentsWidget->item(row, cnopNum)->text();
						
			documentsWidget->item(row, cnopDocument)->setText(fileName);
			
			CMySQL::getInstance()->execQuery(requete);
		}
	}
	setCursor(Qt::ArrowCursor);
}
//------------------------------------------------------------------------------
void CProspectFrm::makeRequete(QString &requete, QString &alias)
{
	requete="SELECT p.code, p.nom, p.adresse1, ";
	requete+="p.adresse2, p.adresse3, p.codePostal, ";
	requete+="p.ville, p.pays, p.telephone, ";
	requete+="p.fax, p.creation, p.activite, p.effectif, ";
	requete+="p.commentaires, p.note, ISNULL(prospect) AS pasClient, p.statusPaie, p.emailing, p.idSociete, p.siteWeb ";
	requete+="FROM "+masterTable+" as p LEFT JOIN client ON prospect=p.code ";
	
	alias="p";
}
//------------------------------------------------------------------------------
void CProspectFrm::showFormulaire(QSqlQuery *query, CGlobal::EAction& action)
{
	QSqlRecord rec=query->record();
	
	curCode=rec.value("code").toString();
	code->setValue(curCode);
	nom->setValue(rec.value("nom"));
	adresse1->setValue(rec.value("adresse1"));
	adresse2->setValue(rec.value("adresse2"));
	adresse3->setValue(rec.value("adresse3"));
	codePostal->setValue(rec.value("codePostal"));
	ville->setValue(rec.value("ville"));
	pays->setValue(rec.value("pays"));
	telephone->setValue(rec.value("telephone"));
	fax->setValue(rec.value("fax"));
	creation->setValue(rec.value("creation"));
	activite->setValue(rec.value("activite"));
	effectif->setCurrentIndex(effectif->findText(rec.value("effectif").toString()));
	commentaires->setValue(rec.value("commentaires").toString());
	note->setValue(rec.value("note"));
	tabWidget->setTabIcon(etnCommentaires, commentaires->getValue() != ""  ? QIcon(":coMexpert/images/irkickflash.png") : QIcon());
	statusPaie->setValue(rec.value("statusPaie"));
	emailing->setValue(rec.value("emailing").toString());
	idSociete->setValue(rec.value("idSociete"));
	siteWeb->setValue(rec.value("siteWeb"));
		
	amor->setPixmap(rec.value("pasClient").toInt() == 0 ? QPixmap(":coMexpert/images/amor.png") : QPixmap());
		
	loadGrilleActions();
	loadGrilleContact();
	loadGrilleDevis();
	loadGrilleDocuments();
	loadGrilleTva();
}
//------------------------------------------------------------------------------
void CProspectFrm::on_actAjouter_triggered(void)
{
	contact->setText("");
	fonction->setText("");
	effectif->setCurrentIndex(0);
	actionWidget->setRowCount(0);
	contactWidget->setRowCount(0);
	devisWidget->setRowCount(0);
	tvaWidget->setRowCount(0);
	tabWidget->setTabIcon(etnCommentaires, QIcon());
	mail->setText("");
	
	setActionCur(CGlobal::acAjout);
	
	creation->setValue(CMySQL::getInstance()->getCurrentDate());
}
//------------------------------------------------------------------------------
void CProspectFrm::on_actValider_triggered(void)
{
	QString requete;
	QString condition;
	
	code->setText(code->text().toUpper());
	calculChamps(getActionCur());
	
	if(!validChamps()) return;
	if(!validLiaison()) return;
	
	switch(getActionCur())
	{
		case CGlobal::acAjout:
			requete="INSERT INTO "+masterTable+" SET "+primaryKey+"=\""+code->getValue()+"\", ";
			requete+="creation=CURDATE(), createur=\""+CMySQL::getInstance()->getUser()+"\", ";
			condition="";
			break;
		case CGlobal::acModif:
			requete="UPDATE "+masterTable+" SET ";
			requete+="modification=CURDATE(), modificateur=\""+CMySQL::getInstance()->getUser()+"\", ";
			condition="WHERE "+primaryKey+"=\""+code->getValue()+"\"";
			break;
		default:
			return;
	}
	
	requete+="nom=\""+nom->getValue()+"\", adresse1=\""+adresse1->getValue()+"\", "; 
	requete+="adresse2=\""+adresse2->getValue()+"\", adresse3=\""+adresse3->getValue()+"\", "; 
	requete+="codePostal=\""+codePostal->getValue()+"\", ville=\""+ville->getValue()+"\", ";
	requete+="telephone=\""+telephone->getValue()+"\", ";
	requete+="fax=\""+fax->getValue()+"\", pays=\""+pays->getValue()+"\", ";
	requete+="activite=\""+activite->getValue()+"\", ";
	requete+="effectif=\""+effectif->currentText()+"\", commentaires=\""+commentaires->getValue()+"\", ";
	requete+="note=\""+note->getValue()+"\", statusPaie=\""+statusPaie->getValue()+"\", ";
	requete+="emailing=\""+emailing->getValue()+"\", idSociete="+idSociete->getValue()+", ";
	requete+="siteWeb=\""+siteWeb->getValue()+"\" ";
	
	requete+=condition;
	
	if(CMySQL::getInstance()->execQuery(requete))
	{
		curCode=code->text();
		setActionCur(CGlobal::acNone);
		tabWidget->setTabIcon(etnCommentaires, commentaires->getValue() != ""  ? QIcon(":coMexpert/images/irkickflash.png") : QIcon());
		loadGrilleTva();
	}
}
//------------------------------------------------------------------------------
void CProspectFrm::on_actAnnuler_triggered(void)
{
	QMessageBox msgBox(	QMessageBox::Question, tr("Confirmation"), 
						tr("Etes vous sûre de vouloir annuler ?"), QMessageBox::Yes | QMessageBox::No);
	msgBox.exec();

	if(msgBox.result() == QMessageBox::Yes)
	{
		if(!chargeDonnees(curCode, CGlobal::seNone))
		{
			if(!chargeDonnees(curCode, CGlobal::sePrecedent))
			{
				if(!chargeDonnees(curCode, CGlobal::seSuivant))
				{
					setActionCur(CGlobal::acTableVide);
					return;
				}
			}
		}
	}
}
//------------------------------------------------------------------------------
void CProspectFrm::on_actSupprimer_triggered(void)
{
	QMessageBox msgBox(	QMessageBox::Question, tr("Confirmation"), 
						tr("Etes vous sûre de vouloir supprimer la fiche courante ?"), QMessageBox::Yes | QMessageBox::No);
	msgBox.exec();
	
	if(msgBox.result() == QMessageBox::Yes)
	{
		QString requete="DELETE FROM "+masterTable+" WHERE "+primaryKey+"=\""+curCode+"\"";

		CMySQL::getInstance()->execQuery(requete);
		
		dropFavoris(favorisMenu);
		loadFavoris(favorisMenu);
		
		if(!chargeDonnees(curCode, CGlobal::sePrecedent))
		{
			if(!chargeDonnees(curCode, CGlobal::seSuivant))
			{
				setActionCur(CGlobal::acTableVide);
			}
		}
	}
}
//------------------------------------------------------------------------------
void CProspectFrm::onChange(void)
{
	if(getActionCur() == CGlobal::acNone)
	{
		setActionCur(CGlobal::acModif);
	}
}
//------------------------------------------------------------------------------
void CProspectFrm::on_actRechercheUneFiche_triggered(void)
{
	CFindFrm *findFrm=new CFindFrm(masterTable, this, "", sizeFrmRecherche, posFrmRecherche, colSortFrmRecherche, sortOrderFrmRecherche, lastLigneFrmRecherche);
	
	findFrm->setModal(true);
	findFrm->exec();
	if(findFrm->result() == QDialog::Accepted)
	{
		chargeDonnees(findFrm->getResult(), CGlobal::seNone);
		derniereRequete=findFrm->getRequete();
		actDerniereRecherche->setToolTip(tr("Dernière recherche \n(")+findFrm->getRequeteHum()+tr(")"));
		setActionCur(getActionCur());
	}
	
	sizeFrmRecherche=findFrm->getSizeResult();
	posFrmRecherche=findFrm->getPosResult();
	colSortFrmRecherche=findFrm->getColSort();
	sortOrderFrmRecherche=findFrm->getSortOrder();
	lastLigneFrmRecherche=findFrm->getLastLigne();
	
	delete findFrm;
}
//------------------------------------------------------------------------------
void CProspectFrm::on_actDerniereRecherche_triggered(void)
{
	CFindFrm *findFrm=new CFindFrm(masterTable, this, derniereRequete, sizeFrmRecherche, posFrmRecherche, colSortFrmRecherche, sortOrderFrmRecherche, lastLigneFrmRecherche);
	
	if(findFrm->result() == QDialog::Accepted)
	{
		chargeDonnees(findFrm->getResult(), CGlobal::seNone);
	}
	
	sizeFrmRecherche=findFrm->getSizeResult();
	posFrmRecherche=findFrm->getPosResult();
	colSortFrmRecherche=findFrm->getColSort();
	sortOrderFrmRecherche=findFrm->getSortOrder();
	lastLigneFrmRecherche=findFrm->getLastLigne();
	
	delete findFrm;
}
//------------------------------------------------------------------------------
void CProspectFrm::on_actAbonneEMailing_triggered(void)
{
	QString eMail=mail->text().section(">", 1, 1).section("<", 0, 0);
	
	if(eMail != "")
	{
		if(!CMySQL::getInstance()->existe("abonneEMailing", "mail", eMail)) 
		{
			QString requete="INSERT INTO abonneEMailing SET id = \""+QUuid::createUuid().toString()+"\", ";
			requete+="mail = \""+eMail+"\", abonne=1, creation=CURDATE(), createur=\""+CMySQL::getInstance()->getUser()+"\", ";
			requete+="societe = \""+nom->getValue()+"\", contact = \""+contact->text()+"\" ";
					
			CMySQL::getInstance()->execQuery(requete);
			
			QMessageBox msgBox(	QMessageBox::Information, tr("Information"), 
								tr("Le prospect a été ajouter aux abonnements EMailing"), QMessageBox::Ok);
			msgBox.exec();
		}else
		{
			QMessageBox msgBox(	QMessageBox::Warning, tr("Attention"), 
								tr("Le prospect a déjà été ajouter aux abonnements EMailing"), QMessageBox::Ok);
			msgBox.exec();
		}
	}
}
//------------------------------------------------------------------------------
void CProspectFrm::on_actCopieAdresse_triggered(void)
{
	QClipboard *clipboard=QApplication::clipboard();
	QString adresse=nom->getValue()+"\n";
	
	if(contact->text() != "") adresse+=contact->text()+"\n";
	adresse+=adresse1->getValue()+"\n";
	if(adresse2->getValue() != "") adresse+=adresse2->getValue()+"\n";
	if(adresse3->getValue() != "") adresse+=adresse3->getValue()+"\n";
	adresse+=codePostal->getValue()+" "+ville->getValue()+"\n";
	
	
	clipboard->setText(adresse);
}
//------------------------------------------------------------------------------
void CProspectFrm::ajouteAction(bool &goToLast, int numContact)
{
	int col;
	QString contactNom;
	QString numeroAction=CMySQL::getInstance()->getNextCode("actionsProspect", "numeroAction", "prospect=\""+curCode+"\"");
	QString requete;
	CGlobal::EAction oldActionCur=getActionCur();
	
	if(numContact == -1)
	{
		contactNom=contact->text();
	}else
	{
		QSqlQuery *query;
		
		requete="SELECT nom FROM contactProspect ";
		requete+="WHERE prospect = \""+curCode+"\" AND numero = "+QString::number(numContact);
				
		if(CMySQL::getInstance()->execQuery(requete, &query))
		{
			if(query->next()) 
			{
				contactNom=query->record().value("nom").toString();
			}
		}
		delete query;
	}
	
	actionWidget->getColumnModel(cnaInterloc)->setDefaultValue(contactNom);
	actionWidget->getColumnModel(cnaNum)->setDefaultValue(numeroAction);
	actionWidget->getColumnModel(cnaQui)->setDefaultValue(CMySQL::getInstance()->getUser());
	actionWidget->getColumnModel(cnaHeure)->setDefaultValue(CMySQL::getInstance()->getCurrentTime().toString("hh:mm:ss"));
	
	requete="INSERT INTO actionsProspect ";
	requete+="SET prospect=\""+curCode+"\", numeroAction="+numeroAction+", ";
	requete+="dateAction=curdate(), interlocuteur=\""+contactNom+"\", ";
	requete+="qui=\""+CMySQL::getInstance()->getUser()+"\", ";
	requete+="heureAction=\""+actionWidget->getColumnModel(cnaHeure)->getDefaultValue()+"\" ";
	
	
	CMySQL::getInstance()->execQuery(requete);
	
	setActionCur(CGlobal::acAddLigne);
	actionWidget->insertRow(0);
	
	for(col=0;col<actionWidget->getColumnModelCount();col++)
	{
		CMyTableWidgetItem *item;
		CColumnModel *columnModel=actionWidget->getColumnModel(col);
				
		item=new CMyTableWidgetItem(columnModel->getDefaultValue(), columnModel->getType());
		item->setTextAlignment(columnModel->getAlignment() | Qt::AlignVCenter);
		item->setIcon(*columnModel->getIcon());
		item->setFlags(columnModel->getFlags());
		
		actionWidget->setItem(0, col, item);
	}
	goToLast=false;
	setActionCur(oldActionCur);
}
//------------------------------------------------------------------------------
void CProspectFrm::supprimeAction(int row, bool& ok)
{
	QTableWidgetItem *item=actionWidget->item(row, 0);
	int numeroAction;
	
	if(item != NULL)
	{
		numeroAction=item->text().toInt();
		
		QMessageBox msgBox(	QMessageBox::Question, tr("Confirmation"), 
							tr("Etes vous sûre de vouloir supprimer la ligne numero ")+
									QString().number(numeroAction)+tr(" ?"), QMessageBox::Yes | QMessageBox::No);
		msgBox.exec();
		
		if(msgBox.result() == QMessageBox::Yes)
		{
			QString requete;
			
			requete="DELETE from actionsProspect WHERE prospect = \""+curCode+"\" AND numeroAction = "+QString().number(numeroAction);
			
			CMySQL::getInstance()->execQuery(requete);

			ok=true;
		}
		
	}
}
//------------------------------------------------------------------------------
void CProspectFrm::on_actDerniereAction_triggered(void)
{
	CDerniereActionFrm *derniereActionFrm=new CDerniereActionFrm(this);
		
	derniereActionFrm->setModal(true);
	derniereActionFrm->exec();
	if(derniereActionFrm->result() == QDialog::Accepted)
	{
		chargeDonnees(derniereActionFrm->getProspect(), CGlobal::seNone);
	}
	delete derniereActionFrm;
}
//------------------------------------------------------------------------------
void CProspectFrm::on_actProspectsSansAction_triggered(void)
{
	QVector<CMySQL::SChampRecherche> vector=CMySQL::getInstance()->getChampsRecherche(masterTable);
	QVector<CMySQL::SChampRecherche>::iterator i = vector.begin();
	QString requete="SELECT ";
	QString champListe="";
	CFindFrm *findFrm;
	
	while(i != vector.end()) 
	{
		if(champListe != "")
		{
			champListe+=", ";
		}
		champListe+=(*i).champNom;
		i++;
	}
	
	requete+=champListe+" FROM "+masterTable+" LEFT JOIN actionsProspect ON prospect=code ";
	requete+="WHERE prospect IS NULL";
	
	findFrm=new CFindFrm(masterTable, this, requete);
	
	if(findFrm->result() == QDialog::Accepted)
	{
		chargeDonnees(findFrm->getResult(), CGlobal::seNone);
	}
	
	delete findFrm;
}
//------------------------------------------------------------------------------
void CProspectFrm::modifiAction(int row, int column)
{
	QString text;
	QString requete;
	QTableWidgetItem *item;
	
	if(getActionCur() != CGlobal::acNone && getActionCur() != CGlobal::acModif) return;
	item=actionWidget->item(row, column);
	
	if(item != NULL && column != cnaNum)
	{
		QString text=actionWidget->getColumnModel(column)->format(item->text());
		QString textSQL=actionWidget->getColumnModel(column)->formatToSQL(CGlobal::addSlashesQuot(item->text()));
		
		requete="UPDATE actionsProspect ";
		requete+="SET "+actionWidget->getColumnModel(column)->getNomChamp()+" = "+textSQL+" ";
		requete+="WHERE prospect=\""+curCode+"\" AND numeroAction="+actionWidget->item(row, cnaNum)->text();
		
		item->setText(text);
		
		CMySQL::getInstance()->execQuery(requete);
		
		actionWidget->resizeRowToContents(row);
	}
}
//------------------------------------------------------------------------------
void CProspectFrm::actionDoubleClicked(int row, int column)
{
	QTableWidgetItem *item;
	CCalendrierFrm *calendrierFrm;
	CComboResultFrm *comboResultFrm;
		
	item=actionWidget->item(row, column);
	if(item->flags() != 0)
	{
		switch(column)
		{
			case cnaDate:
				calendrierFrm=new CCalendrierFrm(this);
				
				calendrierFrm->setDate(QDate::fromString(item->text(), "dd/MM/yyyy"));
				calendrierFrm->exec();
				
				if(calendrierFrm->result() == QDialog::Accepted)
				{
					item->setText(calendrierFrm->getDate().toString("dd/MM/yyyy"));
				}
				
				delete calendrierFrm;
				break;
			case cnaInterloc:
				comboResultFrm=new CComboResultFrm("contactProspect", "nom", this, 1, "prospect = \""+curCode+"\" ");
		
				comboResultFrm->setModal(true);
				comboResultFrm->exec();
		
				if(comboResultFrm->result() == QDialog::Accepted)
				{
					item->setText(comboResultFrm->getResult());
				}
		
				delete comboResultFrm;
				break;
			default:
				break;
		}
	}
}
//------------------------------------------------------------------------------
void CProspectFrm::devisDoubleClicked(int row, int column)
{
	if(column == cndpNum)
	{
		int numero=devisWidget->item(row, column)->text().toInt();
		
		mainFrm->loadDevis(numero);
	}
}
//------------------------------------------------------------------------------
void CProspectFrm::onCombo(CMyComboBox *comboBox)
{
	CComboResultFrm *comboResultFrm=new CComboResultFrm(comboBox->getTableRemp(), comboBox->getChampRemp(), this);
	
	comboResultFrm->setModal(true);
	comboResultFrm->exec();
	
	if(comboResultFrm->result() == QDialog::Accepted)
	{
		comboBox->setValue(comboResultFrm->getResult());
	}
	
	delete comboResultFrm;
}
//------------------------------------------------------------------------------
void CProspectFrm::onMailTo(QString href)
{
	if(href != "")
	{
		QDesktopServices::openUrl(href);
	}
}
//------------------------------------------------------------------------------
void CProspectFrm::ajouteContact(bool &goToLast)
{
	int col;
	int row;
	CGlobal::EAction oldActionCur=getActionCur();
	QString numeroContact=CMySQL::getInstance()->getNextCode("contactProspect", "numero", "prospect=\""+curCode+"\"");
	QString requete="INSERT INTO contactProspect ";
	requete+="SET prospect=\""+curCode+"\", numero="+numeroContact+" ";
	if(numeroContact.toInt() == 1)
	{
		requete+=", defaut=\"X\" ";
		contactWidget->getColumnModel(cncpDefaut)->setDefaultValue("X");
	}else
	{
		contactWidget->getColumnModel(cncpDefaut)->setDefaultValue("");
	}
	
	contactWidget->getColumnModel(cncpNum)->setDefaultValue(numeroContact);
	
	CMySQL::getInstance()->execQuery(requete);
	
	setActionCur(CGlobal::acAddLigne);
	row=contactWidget->addRow();
	
	for(col=0;col<contactWidget->getColumnModelCount();col++)
	{
		CMyTableWidgetItem *item;
		CColumnModel *columnModel=contactWidget->getColumnModel(col);
				
		item=new CMyTableWidgetItem(columnModel->getDefaultValue(), columnModel->getType());
		item->setTextAlignment(columnModel->getAlignment() | Qt::AlignVCenter);
		item->setIcon(*columnModel->getIcon());
		item->setFlags(columnModel->getFlags());
		
		contactWidget->setItem(row, col, item);
		
		tabWidget->setTabText(etnContacts, tr("Contacts")+" ("+QString::number(row+1)+")");
	}
	
	setActionCur(oldActionCur);
}
//------------------------------------------------------------------------------
void CProspectFrm::supprimeContact(int row, bool& ok)
{
	QTableWidgetItem *item=contactWidget->item(row, cncpNum);
	int numeroContact;
	
	if(item != NULL)
	{
		numeroContact=item->text().toInt();
		
		QMessageBox msgBox(	QMessageBox::Question, tr("Confirmation"), 
							tr("Etes vous sûre de vouloir supprimer la ligne numero ")+
									QString().number(numeroContact)+tr(" ?"), QMessageBox::Yes | QMessageBox::No);
		msgBox.exec();
		
		if(msgBox.result() == QMessageBox::Yes)
		{
			QString requete;
			
			requete="DELETE from contactProspect WHERE prospect = \""+curCode+"\" AND numero = "+QString().number(numeroContact);
			
			CMySQL::getInstance()->execQuery(requete);
			
			if(contactWidget->item(row, cncpDefaut)->text() == "X")
			{
				contact->setText("");
				fonction->setText("");
				mail->setText("");
			}
			
			tabWidget->setTabText(etnContacts, tr("Contacts")+" ("+QString::number(contactWidget->rowCount()-1)+")");
			
			ok=true;
		}
	}
}
//------------------------------------------------------------------------------
void CProspectFrm::modifiContact(int row, int column)
{
	QString text;
	QString requete;
	QTableWidgetItem *item;
	
	if(getActionCur() != CGlobal::acNone && getActionCur() != CGlobal::acModif) return;
	item=contactWidget->item(row, column);
	
	if(item != NULL && column != cncpNum)
	{
		QString text=contactWidget->getColumnModel(column)->format(item->text());
		QString textSQL=contactWidget->getColumnModel(column)->formatToSQL(CGlobal::addSlashesQuot(item->text()));
		
		requete="UPDATE contactProspect ";
		requete+="SET "+contactWidget->getColumnModel(column)->getNomChamp()+" = "+textSQL+" ";
		requete+="WHERE prospect=\""+curCode+"\" AND numero="+contactWidget->item(row, cncpNum)->text();
		
		item->setText(text);
		
		CMySQL::getInstance()->execQuery(requete);
		
		if(contactWidget->item(row, cncpDefaut)->text() == "X")
		{
			contact->setText(contactWidget->item(row, cncpNom)->text());
			fonction->setText(contactWidget->item(row, cncpFonction)->text());
			mail->setText(QString("<a href=\"mailto:%1\">%1</a>").arg(contactWidget->item(row, cncpMail)->text()));
		}
		
		contactWidget->resizeRowToContents(row);
	}
}
//------------------------------------------------------------------------------
void CProspectFrm::contactDoubleClicked(int row, int column)
{
	QString requete;
	QTableWidgetItem *item;
	int i;
	
	if(getActionCur() != CGlobal::acNone && getActionCur() != CGlobal::acModif) return;
	
	if(column == cncpDefaut)
	{
		item=contactWidget->item(row, column);
		
		if(item->text() != "X")
		{
			requete="UPDATE contactProspect SET defaut=\"\" WHERE prospect=\""+curCode+"\" ";
			CMySQL::getInstance()->execQuery(requete);
			
			for(i=0;i<contactWidget->rowCount();i++)
			{
				contactWidget->item(i, column)->setText("");
			}
			
			requete="UPDATE contactProspect ";
			requete+="SET defaut=\"X\" ";
			requete+="WHERE prospect=\""+curCode+"\" AND numero="+contactWidget->item(row, cncpNum)->text();
			CMySQL::getInstance()->execQuery(requete);
			
			item->setText("X");
			
			contact->setText(contactWidget->item(row, cncpNom)->text());
			fonction->setText(contactWidget->item(row, cncpFonction)->text());
			mail->setText(QString("<a href=\"mailto:%1\">%1</a>").arg(contactWidget->item(row, cncpMail)->text()));
		}
	}
}
//------------------------------------------------------------------------------
void CProspectFrm::tableCustomContextMenuRequested(const QPoint & pos)
{
	QTableWidgetItem *item=contactWidget->item(contactWidget->currentRow(), cncpNum);
	
	if(item != NULL)
	{
		curContactNum=item->text().toInt();
		actMailFromContact->setEnabled(contactWidget->item(contactWidget->currentRow(), cncpMail)->text() != "");
		popupMenu->popup(contactWidget->mapToGlobal(pos));
	}
}
//------------------------------------------------------------------------------
void CProspectFrm::actActionFromContact_triggered(void)
{
	if(curContactNum != -1)
	{
		bool goToLast=false;
		ajouteAction(goToLast, curContactNum);
		tabWidget->setCurrentIndex(0);
		
		curContactNum=-1;
	}
}
//------------------------------------------------------------------------------
void CProspectFrm::on_actFavoris_triggered(void) {
	favorisMenu->popup(QCursor::pos());
}
//------------------------------------------------------------------------------
void CProspectFrm::actNouveauFavoris_triggered(void) {
	QAction *sender=(QAction *)QObject::sender();
	QString requete;
	QVariant parentId=sender->data();
	QSqlQuery *query;
	
	if(parentId.isNull()) {
		requete="SELECT id FROM favorisProspect WHERE parent IS NULL AND user=\""+CMySQL::getInstance()->getUser()+"\"";
		if(CMySQL::getInstance()->execQuery(requete, &query)) {
			if(!query->next()) {
				requete="INSERT INTO favorisProspect SET user=\""+CMySQL::getInstance()->getUser()+"\"";
				
				CMySQL::getInstance()->execQuery(requete, true, &parentId);
			}else {
				parentId=query->record().value("id");
			}
		}
		delete query;
	}
	
	requete="INSERT INTO favorisProspect SET ";
	requete+="user=\""+CMySQL::getInstance()->getUser()+"\", prospect=\""+curCode+"\", parent="+parentId.toString();
	
	if(CMySQL::getInstance()->execQuery(requete)) {
		dropFavoris(favorisMenu);
		loadFavoris(favorisMenu);
	}	
}
//------------------------------------------------------------------------------
void CProspectFrm::actGestFavoris_triggered(void)
{
	CGestionFavorisProspectFrm *gestionFavorisFrm=new CGestionFavorisProspectFrm(this);
	
	gestionFavorisFrm->exec();
	
	dropFavoris(favorisMenu);
	loadFavoris(favorisMenu);
	
	delete gestionFavorisFrm;
}
//------------------------------------------------------------------------------
void CProspectFrm::actSelectFavoris_triggered(void)
{
	QAction *act = qobject_cast<QAction *>(this->sender());

	chargeDonnees(act->data().toString(), CGlobal::seNone);
}
//------------------------------------------------------------------------------
void CProspectFrm::actMailFromContact_triggered(void)
{
	QString href=QString("mailto:%1").arg(contactWidget->item(contactWidget->currentRow(), cncpMail)->text());
	QDesktopServices::openUrl(href);
}
//------------------------------------------------------------------------------
void CProspectFrm::onInvokeHelp(CChamp *champ)
{
	CHelp::getInstance()->startHelp("setSource qthelp://alpes-ressources.com.coMexpert-"+VERSION_LOGICIEL+"/doc/prospect.html#"+champ->getTable()+"."+champ->getChamp());
}
//------------------------------------------------------------------------------
void CProspectFrm::ajouteDocument(bool &goToLast)
{
	int col;
	int row;
	QString numero=CMySQL::getInstance()->getNextCode("documentsProspect", "numero", "prospect=\""+curCode+"\"");
	QString requete="INSERT INTO documentsProspect ";
	requete+="SET prospect=\""+curCode+"\", numero="+numero+", createur=\""+CMySQL::getInstance()->getUser()+"\", creation=CURDATE() ";
	
	documentsWidget->getColumnModel(cnopNum)->setDefaultValue(numero);
	
	CMySQL::getInstance()->execQuery(requete);
	
	setActionCur(CGlobal::acAddLigne);
	row=documentsWidget->addRow();
	
	for(col=0;col<documentsWidget->getColumnModelCount();col++)
	{
		CMyTableWidgetItem *item;
		CColumnModel *columnModel=documentsWidget->getColumnModel(col);
				
		item=new CMyTableWidgetItem(columnModel->getDefaultValue(), columnModel->getType());
		item->setTextAlignment(columnModel->getAlignment() | Qt::AlignVCenter);
		item->setIcon(*columnModel->getIcon());
		item->setFlags(columnModel->getFlags());
		
		documentsWidget->setItem(row, col, item);
	}
	
	creerDocument(row);
	setActionCur(CGlobal::acNone);
}
//------------------------------------------------------------------------------
void CProspectFrm::supprimeDocument(int row, bool& ok)
{
	QTableWidgetItem *item=documentsWidget->item(row, cnopNum);
	int numero;
	
	if(item != NULL)
	{
		numero=item->text().toInt();
		
		QMessageBox msgBox(	QMessageBox::Question, tr("Confirmation"), 
							tr("Etes vous sûre de vouloir supprimer le document numero ")+
									QString::number(numero)+tr(" ?"), QMessageBox::Yes | QMessageBox::No);
		msgBox.exec();
		
		if(msgBox.result() == QMessageBox::Yes)
		{
			QString requete;
			
			requete="DELETE from documentsProspect WHERE prospect = \""+curCode+"\" AND numero = "+QString::number(numero);
			
			CMySQL::getInstance()->execQuery(requete);
			
			ok=true;
		}
		
	}
}
//------------------------------------------------------------------------------
void CProspectFrm::modifiDocument(int row, int column)
{
	QString requete;
	QTableWidgetItem *item;
	
	if(getActionCur() != CGlobal::acNone) return;
	item=documentsWidget->item(row, column);
	
	if(item != NULL)
	{
		QString text=documentsWidget->getColumnModel(column)->format(item->text());
		QString textSQL=documentsWidget->getColumnModel(column)->formatToSQL(CGlobal::addSlashesQuot(item->text()));
		
		requete="UPDATE documentsProspect ";
		requete+="SET "+documentsWidget->getColumnModel(column)->getNomChamp()+" = "+textSQL+", ";
		requete+="modificateur=\""+CMySQL::getInstance()->getUser()+"\", modification=CURDATE() ";
		requete+="WHERE prospect=\""+curCode+"\" AND numero="+documentsWidget->item(row, cnopNum)->text();
		
		item->setText(text);
		
		CMySQL::getInstance()->execQuery(requete);
		
		documentsWidget->resizeRowToContents(row);
	}
}
//------------------------------------------------------------------------------
void CProspectFrm::documentDoubleClicked(int row, int column)
{
	QString url;
	
	switch(column)
	{
		case cnopDocument:
			url=CGlobal::getConfig().value("HTTPHost").toString()+"/getDocumentProspect.php?prospect="+curCode+"&numero="+documentsWidget->item(row, cnopNum)->text();
	
			QDesktopServices::openUrl(QUrl(url));
			break;
		case cnopNum:
			creerDocument(row);
			break;
		default:
			break;
	}
}
//------------------------------------------------------------------------------
void CProspectFrm::beforeInsertAction(const QSqlQuery *query, CMyTableWidgetItem *item)
{
	if((query->record().value("auto").toInt() == 1)) 
	{
		item->setBackground(QBrush(QColor(170, 255, 170)));
	}
}
//------------------------------------------------------------------------------
void CProspectFrm::beforeChangeRecordContact(const QSqlQuery *query, int row)
{
	if(contactWidget->item(row, cncpDefaut)->text() == "X")
	{
		contact->setText(contactWidget->item(row, cncpNom)->text());
		fonction->setText(contactWidget->item(row, cncpFonction)->text());
		mail->setText(QString("<a href=\"mailto:%1\">%1</a>").arg(contactWidget->item(row, cncpMail)->text()));
	}
}
//------------------------------------------------------------------------------
void CProspectFrm::on_siteWeb_clickWithCtrl(void) {
	QDesktopServices::openUrl(siteWeb->getValue());
}
//------------------------------------------------------------------------------
void CProspectFrm::modifiTva(int row, int column) {
	QString text;
	QString requete;
	QTableWidgetItem *item;
	
	if(getActionCur() != CGlobal::acNone) return;
	item=tvaWidget->item(row, column);
	
	if(column != ctnpId )
	{
		QString text=tvaWidget->getColumnModel(column)->format(item->text());
		QString textSQL=tvaWidget->getColumnModel(column)->formatToSQL(CGlobal::addSlashesQuot(item->text()));
		QString nomChamp=tvaWidget->getColumnModel(column)->getNomChamp();
		int id=tvaWidget->item(row, ctnpId)->text().toInt();
		
		requete="UPDATE tvaProspect ";
		requete+="SET "+nomChamp+"="+textSQL+", modification=CURDATE(), ";
		requete+="modificateur=\""+CMySQL::getInstance()->getUser()+"\", custom=\"OUI\" ";
		requete+="WHERE id="+QString::number(id);
		
		CMySQL::getInstance()->execQuery(requete);
	}
}
//------------------------------------------------------------------------------